<?php
namespace app\index\controller;

use app\common\model\Order;
use app\common\model\Pays;
use app\common\model\Users;
use app\common\model\Weblist;
use think\Db;

class Epay extends Common
{


    private $userInfo;

    private $epay_config;

    private $authController = array(
        'vip_Notify',
        'pe_Notify',
        'dl_Notify',
        'fz_Notify'
    );

    public function _empty()
    {
        exit($this->fetch('pc/common/empty'));
    }

    public function __construct()
    {
        parent:: __construct();
        Vendor('Epay.Epayconfig');
        Vendor('Epay.Epaynotify');
        Vendor('Epay.Epaysubmit');
        $this->epay_config = [
            'partner' => config('sys_epay_id'),
            'key' => config('sys_epay_key'),
            'sign_type' => strtoupper('MD5'),
            'input_charset' => strtolower('utf-8'),
            'transport' => 'http',
            'apiurl' => config('sys_epay_url')
        ];
        $this->codepay_config = [
            'id' => config('sys_codepay_id'),
            'key' => config('sys_codepay_key'),
            'chart' => strtolower('utf-8'),
            'act' => 1,
            'page' => 4,
            'style' => 1,
            'outTime' => 300,
            'min' => 0.01,
            'pay_type' => 1
        ];
    }

    public function submit()
    {
        $data = input('get.');
        if (!isset($data['type'])) {
            $this->assign('alert', 'NO TYPE！');
            $this->assign('url', '/pc/index/act/user.html');
            if(check_mobile()){
				exit($this->fetch('mobile/common/msg'));
			}else{
				exit($this->fetch('pc/common/msg'));
			}
        } elseif (!$order = Pays::where('orderid', '=', $data['orderid'])->find()) {
            $this->assign('alert', '该订单号不存在，请重新发起支付请求');
            $this->assign('url', '/pc/index/act/user.html');
            if(check_mobile()){
				exit($this->fetch('mobile/common/msg'));
			}else{
				exit($this->fetch('pc/common/msg'));
			}
        } else {
            exit(Pay($order['orderid'], $order['name'], $order['money'], $order['type'], $order['shop'], $order['shopid']));
        }
    }

    public function vip_Return()
    {
        $data = input('get.');
        $alipayNotify = new \AlipayNotify($this->epay_config);
        $verify_result = $alipayNotify->verifyReturn();
        if ($verify_result) {
            $pay_order = Pays::findByOrderId($data['out_trade_no']);
            $order = [
                'type' => '' . $pay_order['type'] . '',
                'orderid' => $data['out_trade_no'],
                'trade_no' => $data['trade_no'],
                'time' => date("Y-m-d H:i:s"),
                'name' => $pay_order['name'],
                'money' => $pay_order['money'],
                'status' => 2,
                'zid' => WEB_ID,
            ];
            if ($data['trade_status'] == 'TRADE_FINISHED' || $data['trade_status'] == 'TRADE_SUCCESS') {
                if ($pay_order['status'] == 0) {
                    Order::add($order);
                    Pays::updateByOrderId($data['out_trade_no'], ['status' => 2, 'endtime' => date("Y-m-d H:i:s")]);
                    $start_time = is_Vip_Day($pay_order['shopid']);
                    //开通时间
                    $vip_start = date("Y-m-d");
                    //计算开通的vip时长
                    if ($this->userInfo['viptime']) {
                        $vip_time = date("Y-m-d", strtotime("+" . $start_time . " day", strtotime($this->userInfo['viptime'])));
                    } else {
                        $vip_time = date("Y-m-d", strtotime("+" . $start_time . " day"));
                    }
                    Users::where('uid', '=', $this->userInfo['uid'])
                        ->update([
                            'vipstart' => $vip_start,
                            'viptime' => $vip_time
                        ]);
                } else {
                    $this->assign('alert', '开通' . $pay_order['name'] . '成功，感谢您的购买');
                    $this->assign('url', '/pc/index/act/user.html');
                    if(check_mobile()){
						exit($this->fetch('mobile/common/msg'));
					}else{
						exit($this->fetch('pc/common/msg'));
					}
                }
                $this->assign('alert', '开通' . $pay_order['name'] . '成功，感谢您的购买');
                $this->assign('url', '/pc/index/act/user.html');
                if(check_mobile()){
					exit($this->fetch('mobile/common/msg'));
				}else{
					exit($this->fetch('pc/common/msg'));
				}
            } else {
                return "trade_status=" . $data['trade_status'];
            }
        } else {
            $this->assign('alert', '订单效验失败！');
            $this->assign('url', '/pc/index/act/user.html');
            if(check_mobile()){
				exit($this->fetch('mobile/common/msg'));
			}else{
				exit($this->fetch('pc/common/msg'));
			}
        }
    }

    public function vip_Notify()
    {
        $data = input('get.');
        $alipayNotify = new \AlipayNotify($this->epay_config);
        $verify_result = $alipayNotify->verifyReturn();
        if ($verify_result) {
            $pay_order = Pays::findByOrderId($data['out_trade_no']);
            $order = [
                'type' => '' . $pay_order['type'] . '',
                'orderid' => $data['out_trade_no'],
                'trade_no' => $data['trade_no'],
                'time' => date("Y-m-d H:i:s"),
                'name' => $pay_order['name'],
                'money' => $pay_order['money'],
                'status' => 2,
                'zid' => WEB_ID,
            ];
            Order::add($order);
            if ($data['trade_status'] == 'TRADE_FINISHED') {
            } else if ($data['trade_status'] == 'TRADE_SUCCESS' && $pay_order['status'] == 0) {
                Pays::updateByOrderId($data['out_trade_no'], ['status' => 2, 'endtime' => date("Y-m-d H:i:s")]);
                $start_time = is_Vip_Day($pay_order['shopid']);
                //开通时间
                $vip_start = date("Y-m-d");
                //计算开通的vip时长
                if ($this->userInfo['viptime']) {
                    $vip_time = date("Y-m-d", strtotime("+" . $start_time . " day", strtotime($this->userInfo['viptime'])));
                } else {
                    $vip_time = date("Y-m-d", strtotime("+" . $start_time . " day"));
                }
                Users::where('uid', '=', $this->userInfo['uid'])
                    ->update([
                        'vipstart' => $vip_start,
                        'viptime' => $vip_time
                    ]);
            }
            return 'success';
        } else {
            return 'full';
        }
    }

    public function pe_Return()
    {
        $data = input('get.');
        $alipayNotify = new \AlipayNotify($this->epay_config);
        $verify_result = $alipayNotify->verifyReturn();
        if ($verify_result) {
            $pay_order = Pays::findByOrderId($data['out_trade_no']);
            $order = [
                'type' => '' . $pay_order['type'] . '',
                'orderid' => $data['out_trade_no'],
                'trade_no' => $data['trade_no'],
                'time' => date("Y-m-d H:i:s"),
                'name' => $pay_order['name'],
                'money' => $pay_order['money'],
                'status' => 2,
                'zid' => WEB_ID,
            ];
            if ($data['trade_status'] == 'TRADE_FINISHED' || $data['trade_status'] == 'TRADE_SUCCESS') {
                if ($pay_order['status'] == 0) {
                    Order::add($order);
                    Pays::updateByOrderId($data['out_trade_no'], ['status' => 2, 'endtime' => date("Y-m-d H:i:s")]);
                    $peie_Num = is_Peie_Num($pay_order['shopid']);
                    $now_Num = $this->userInfo['peie'] + $peie_Num;
                    Users::where('uid', '=', $this->userInfo['uid'])
                        ->update([
                            'peie' => $now_Num,
                        ]);
                } else {
                    $this->assign('alert', '购买' . $pay_order['name'] . '成功，感谢您的购买');
                    $this->assign('url', '/pc/index/act/user.html');
                    if(check_mobile()){
						exit($this->fetch('mobile/common/msg'));
					}else{
						exit($this->fetch('pc/common/msg'));
					}
                }
                $this->assign('alert', '购买' . $pay_order['name'] . '成功，感谢您的购买');
                $this->assign('url', '/pc/index/act/user.html');
                if(check_mobile()){
					exit($this->fetch('mobile/common/msg'));
				}else{
					exit($this->fetch('pc/common/msg'));
				}
            } else {
                return "trade_status=" . $data['trade_status'];
            }
        } else {
            $this->assign('alert', '订单效验失败！');
            $this->assign('url', '/pc/index/act/user.html');
            if(check_mobile()){
				exit($this->fetch('mobile/common/msg'));
			}else{
				exit($this->fetch('pc/common/msg'));
			}
        }
    }

    public function pe_Notify()
    {
        $data = input('get.');
        $alipayNotify = new \AlipayNotify($this->epay_config);
        $verify_result = $alipayNotify->verifyReturn();
        if ($verify_result) {
            $pay_order = Pays::findByOrderId($data['out_trade_no']);
            $order = [
                'type' => '' . $pay_order['type'] . '',
                'orderid' => $data['out_trade_no'],
                'trade_no' => $data['trade_no'],
                'time' => date("Y-m-d H:i:s"),
                'name' => $pay_order['name'],
                'money' => $pay_order['money'],
                'status' => 2,
                'zid' => WEB_ID,
            ];
            Order::add($order);
            if ($data['trade_status'] == 'TRADE_FINISHED') {
            } else if ($data['trade_status'] == 'TRADE_SUCCESS' && $pay_order['status'] == 0) {
                Pays::updateByOrderId($data['out_trade_no'], ['status' => 2, 'endtime' => date("Y-m-d H:i:s")]);
                $peie_Num = is_Peie_Num($pay_order['shopid']);
                $now_Num = $this->userInfo['peie'] + $peie_Num;
                Users::where('uid', '=', $this->userInfo['uid'])
                    ->update([
                        'peie' => $now_Num,
                    ]);
            }
            return 'success';
        } else {
            return 'full';
        }
    }

    public function dl_Return()
    {
        $data = input('get.');
        $alipayNotify = new \AlipayNotify($this->epay_config);
        $verify_result = $alipayNotify->verifyReturn();
        if ($verify_result) {
            $pay_order = Pays::findByOrderId($data['out_trade_no']);
            $order = [
                'type' => '' . $pay_order['type'] . '',
                'orderid' => $data['out_trade_no'],
                'trade_no' => $data['trade_no'],
                'time' => date("Y-m-d H:i:s"),
                'name' => $pay_order['name'],
                'money' => $pay_order['money'],
                'status' => 2,
                'zid' => WEB_ID,
            ];
            if ($data['trade_status'] == 'TRADE_FINISHED' || $data['trade_status'] == 'TRADE_SUCCESS') {
                if ($pay_order['status'] == 0) {
                    Order::add($order);
                    Pays::updateByOrderId($data['out_trade_no'], ['status' => 2, 'endtime' => date("Y-m-d H:i:s")]);
                    $power = $pay_order['shopid'];
                    //开通时间
                    $vip_start = date("Y-m-d");
                    //计算开通的vip时长
                    if ($this->userInfo['viptime']) {
                        $vip_time = date("Y-m-d", strtotime("+" . config('sys_dl_give_vip_' . $power . '') . " day", strtotime($this->userInfo['viptime'])));
                    } else {
                        $vip_time = date("Y-m-d", strtotime("+" . config('sys_dl_give_vip_' . $power . '') . " day"));
                    }
                    $give = [
                        'dlpower' => $power,
                        'vipstart' => $vip_start,
                        'viptime' => $vip_time,
                        'money' => $this->userInfo['money'] + config('sys_dl_give_rmb_' . $power . ''),
                        'dlzk' => config('sys_dl_give_z_' . $power . '')
                    ];
                    //修改用户信息
                    Users::where('uid', '=', $this->userInfo['uid'])
                        ->field('dlpower,vipstart,viptime,money,dlzk')
                        ->update($give);
                } else {
                    $this->assign('alert', '开通' . $pay_order['name'] . '成功，感谢您的购买');
                    $this->assign('url', '/pc/index/act/user.html');
                    if(check_mobile()){
						exit($this->fetch('mobile/common/msg'));
					}else{
						exit($this->fetch('pc/common/msg'));
					}
                }
                $this->assign('alert', '开通' . $pay_order['name'] . '成功，感谢您的购买');
                $this->assign('url', '/pc/index/act/user.html');
                if(check_mobile()){
					exit($this->fetch('mobile/common/msg'));
				}else{
					exit($this->fetch('pc/common/msg'));
				}
            } else {
                return "trade_status=" . $data['trade_status'];
            }
        } else {
            $this->assign('alert', '订单效验失败！');
            $this->assign('url', '/pc/index/act/user.html');
            if(check_mobile()){
				exit($this->fetch('mobile/common/msg'));
			}else{
				exit($this->fetch('pc/common/msg'));
			}
        }
    }

    public function dl_Notify()
    {
        $data = input('get.');
        $alipayNotify = new \AlipayNotify($this->epay_config);
        $verify_result = $alipayNotify->verifyReturn();
        if ($verify_result) {
            $pay_order = Pays::findByOrderId($data['out_trade_no']);
            $order = [
                'type' => '' . $pay_order['type'] . '',
                'orderid' => $data['out_trade_no'],
                'trade_no' => $data['trade_no'],
                'time' => date("Y-m-d H:i:s"),
                'name' => $pay_order['name'],
                'money' => $pay_order['money'],
                'status' => 2,
                'zid' => WEB_ID,
            ];
            Order::add($order);
            if ($data['trade_status'] == 'TRADE_FINISHED') {
            } else if ($data['trade_status'] == 'TRADE_SUCCESS' && $pay_order['status'] == 0) {
                Pays::updateByOrderId($data['out_trade_no'], ['status' => 2, 'endtime' => date("Y-m-d H:i:s")]);
                $power = $pay_order['shopid'];
                //开通时间
                $vip_start = date("Y-m-d");
                //计算开通的vip时长
                if ($this->userInfo['viptime']) {
                    $vip_time = date("Y-m-d", strtotime("+" . config('sys_dl_give_vip_' . $power . '') . " day", strtotime($this->userInfo['viptime'])));
                } else {
                    $vip_time = date("Y-m-d", strtotime("+" . config('sys_dl_give_vip_' . $power . '') . " day"));
                }
                $give = [
                    'dlpower' => $power,
                    'vipstart' => $vip_start,
                    'viptime' => $vip_time,
                    'money' => $this->userInfo['money'] + config('sys_dl_give_rmb_' . $power . ''),
                    'dlzk' => config('sys_dl_give_z_' . $power . '')
                ];
                //修改用户信息
                Users::where('uid', '=', $this->userInfo['uid'])
                    ->field('dlpower,vipstart,viptime,money,dlzk')
                    ->update($give);
            }
            return 'success';
        } else {
            return 'full';
        }
    }

    public function rmb_Return()
    {
        $data = input('get.');
        $alipayNotify = new \AlipayNotify($this->epay_config);
        $verify_result = $alipayNotify->verifyReturn();
        if ($verify_result) {
            $pay_order = Pays::findByOrderId($data['out_trade_no']);
            $order = [
                'type' => '' . $pay_order['type'] . '',
                'orderid' => $data['out_trade_no'],
                'trade_no' => $data['trade_no'],
                'time' => date("Y-m-d H:i:s"),
                'name' => $pay_order['name'],
                'money' => $pay_order['money'],
                'status' => 2,
                'zid' => WEB_ID,
            ];
            if ($data['trade_status'] == 'TRADE_FINISHED' || $data['trade_status'] == 'TRADE_SUCCESS') {
                if ($pay_order['status'] == 0) {
                    Order::add($order);
                    Pays::updateByOrderId($data['out_trade_no'], ['status' => 2, 'endtime' => date("Y-m-d H:i:s")]);
                    $cz_money = $pay_order['money'];
                    $res_money = $this->userInfo['money'] + $cz_money;
                    //修改用户信息
                    Users::where('uid', '=', $this->userInfo['uid'])
                        ->field('money')
                        ->update([
                            'money' => $res_money,
                        ]);
                } else {
                    $this->assign('alert', '充值' . $pay_order['name'] . '成功，感谢您的购买');
                    $this->assign('url', '/pc/index/act/user.html');
                    if(check_mobile()){
						exit($this->fetch('mobile/common/msg'));
					}else{
						exit($this->fetch('pc/common/msg'));
					}
                }
                $this->assign('alert', '充值' . $pay_order['name'] . '成功，感谢您的购买');
                $this->assign('url', '/pc/index/act/user.html');
                if(check_mobile()){
					exit($this->fetch('mobile/common/msg'));
				}else{
					exit($this->fetch('pc/common/msg'));
				}
            } else {
                return "trade_status=" . $data['trade_status'];
            }
        } else {
            $this->assign('alert', '订单效验失败！');
            $this->assign('url', '/pc/index/act/user.html');
            if(check_mobile()){
				exit($this->fetch('mobile/common/msg'));
			}else{
				exit($this->fetch('pc/common/msg'));
			}
        }
    }

    public function rmb_Notify()
    {
        $data = input('get.');
        $alipayNotify = new \AlipayNotify($this->epay_config);
        $verify_result = $alipayNotify->verifyReturn();
        if ($verify_result) {
            $pay_order = Pays::findByOrderId($data['out_trade_no']);
            $order = [
                'type' => '' . $pay_order['type'] . '',
                'orderid' => $data['out_trade_no'],
                'trade_no' => $data['trade_no'],
                'time' => date("Y-m-d H:i:s"),
                'name' => $pay_order['name'],
                'money' => $pay_order['money'],
                'status' => 2,
                'zid' => WEB_ID,
            ];
            Order::add($order);
            if ($data['trade_status'] == 'TRADE_FINISHED') {
            } else if ($data['trade_status'] == 'TRADE_SUCCESS' && $pay_order['status'] == 0) {
                Pays::updateByOrderId($data['out_trade_no'], ['status' => 2, 'endtime' => date("Y-m-d H:i:s")]);
                $cz_money = $pay_order['shopid'];
                $res_money = $this->userInfo['money'] + $cz_money;
                //修改用户信息
                Users::where('uid', '=', $this->userInfo['uid'])
                    ->field('money')
                    ->update([
                        'money' => $res_money,
                    ]);
            }
            return 'success';
        } else {
            return 'full';
        }
    }

    public function fz_Return()
    {
        $data = input('get.');
        $alipayNotify = new \AlipayNotify($this->epay_config);
        $verify_result = $alipayNotify->verifyReturn();
        if ($verify_result) {
            $pay_order = Pays::findByOrderId($data['out_trade_no']);
            $order = [
                'type' => '' . $pay_order['type'] . '',
                'orderid' => $data['out_trade_no'],
                'trade_no' => $data['trade_no'],
                'time' => date("Y-m-d H:i:s"),
                'name' => $pay_order['name'],
                'money' => $pay_order['money'],
                'status' => 2,
                'zid' => WEB_ID,
            ];
            if ($data['trade_status'] == 'TRADE_FINISHED' || $data['trade_status'] == 'TRADE_SUCCESS') {
                if ($pay_order['status'] == 0) {
                    Order::add($order);
                    Pays::updateByOrderId($data['out_trade_no'], ['status' => 2, 'endtime' => date("Y-m-d H:i:s")]);
                    $is_kt_day = is_fz_add_day($pay_order['shopid']);//获取开通天数
                    $kt_time = date("Y-m-d", strtotime("+" . $is_kt_day . " day"));
                    $prefix = get_prefix() . '_';
                    $addfz = [
                        'domain' => cookie('ktfz_url'),
                        'prefix' => $prefix,
                        'sup_id' => WEB_ID,
                        'web_key' => getRandStr(16),
                        'start_time' => date("Y-m-d"),
                        'user_id' => $this->userInfo['uid'],
                        'webname' => $pay_order['name'],
                        'user_qq' => $this->userInfo['qq'],
                        'mail' => $this->userInfo['mail'],
                        'end_time' => $kt_time
                    ];
                    Weblist::field('sup_id,user_id,webname,domain,user_qq,mail,start_time,end_time,prefix,web_key')->insert($addfz);
                    $sqls = file_get_contents(ROOT_PATH . '/Other/site.sql');
                    $sqls = str_replace('zy_', $prefix, $sqls);
                    $explode = explode(';', $sqls);
                    foreach ($explode as $sql) {
                        if ($sql = trim($sql)) {
                            Db::query($sql);
                        }
                    }
                    //修改用户信息
                    Users::where('uid', '=', $this->userInfo['uid'])
                        ->update(['power' => 9]);
                } else {
                    $this->assign('alert', '开通分站：' . $pay_order['name'] . '成功，感谢您的购买');
                    $this->assign('url', 'http://' . cookie('ktfz_url') . '/');
                    cookie('ktfz_url', null);
                    if(check_mobile()){
						exit($this->fetch('mobile/common/msg'));
					}else{
						exit($this->fetch('pc/common/msg'));
					}
                }
                $this->assign('alert', '开通分站：' . $pay_order['name'] . '成功，感谢您的购买');
                $this->assign('url', 'http://' . cookie('ktfz_url') . '/');
                cookie('ktfz_url', null);
                if(check_mobile()){
					exit($this->fetch('mobile/common/msg'));
				}else{
					exit($this->fetch('pc/common/msg'));
				}
            } else {
                return "trade_status=" . $data['trade_status'];
            }
        } else {
            $this->assign('alert', '订单效验失败！');
            $this->assign('url', '/pc/index/act/user.html');
            if(check_mobile()){
				exit($this->fetch('mobile/common/msg'));
			}else{
				exit($this->fetch('pc/common/msg'));
			}
        }
    }

    public function fz_Notify()
    {
        $data = input('get.');
        $alipayNotify = new \AlipayNotify($this->epay_config);
        $verify_result = $alipayNotify->verifyReturn();
        if ($verify_result) {
            $pay_order = Pays::findByOrderId($data['out_trade_no']);
            $order = [
                'type' => '' . $pay_order['type'] . '',
                'orderid' => $data['out_trade_no'],
                'trade_no' => $data['trade_no'],
                'time' => date("Y-m-d H:i:s"),
                'name' => $pay_order['name'],
                'money' => $pay_order['money'],
                'status' => 2,
                'zid' => WEB_ID,
            ];
            Order::add($order);
            if ($data['trade_status'] == 'TRADE_FINISHED') {
            } else if ($data['trade_status'] == 'TRADE_SUCCESS' && $pay_order['status'] == 0) {
                Pays::updateByOrderId($data['out_trade_no'], ['status' => 2, 'endtime' => date("Y-m-d H:i:s")]);
                $is_kt_day = is_fz_add_day($pay_order['shopid']);//获取开通天数
                $kt_time = date("Y-m-d", strtotime("+" . $is_kt_day . " day"));
                $prefix = get_prefix() . '_';
                $addfz = [
                    'domain' => cookie('ktfz_url'),
                    'prefix' => $prefix,
                    'sup_id' => WEB_ID,
                    'web_key' => getRandStr(16),
                    'start_time' => date("Y-m-d"),
                    'user_id' => $this->userInfo['uid'],
                    'webname' => $pay_order['name'],
                    'user_qq' => $this->userInfo['qq'],
                    'mail' => $this->userInfo['mail'],
                    'end_time' => $kt_time
                ];
                Weblist::field('sup_id,user_id,webname,domain,user_qq,mail,start_time,end_time,prefix,web_key')->insert($addfz);
                $sqls = file_get_contents(ROOT_PATH . '/Other/site.sql');
                $sqls = str_replace('zy_', $prefix, $sqls);
                $explode = explode(';', $sqls);
                foreach ($explode as $sql) {
                    if ($sql = trim($sql)) {
                        Db::query($sql);
                    }
                }
                //修改用户信息
                Users::where('uid', '=', $this->userInfo['uid'])
                    ->update(['power' => 9]);
            }
            return 'success';
        } else {
            return 'full';
        }
    }

    protected
    function _initialize()
    {
        parent::_initialize();
        $this->checkLogin();
		
    }
	
	private
    function checkLogin()
    {
        $check_Login = Users::checkLogin();
        if ($check_Login != null) {
            $this->assign('alert', $check_Login['msg']);
            $this->assign('url', $check_Login['url']);
            if(check_mobile()){
				exit($this->fetch('mobile/common/msg'));
			}else{
				exit($this->fetch('pc/common/msg'));
			}
        } else {
            $this->userInfo = Users::getLoginUser();
            $this->assign('userInfo', $this->userInfo);

        }
    }
}